from django.shortcuts import render
from django.views import View
import re
from django import http

from apps.carts.utils import merge_cart_cookie_to_redis
from apps.users.models import User, Address
import json
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
from django.utils.decorators import method_decorator
from meiduo_demo_1.utils.view import my_decorator, LoginRequiredMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from django.core.mail import send_mail
from celery_tasks.email.tasks import send_email_func
from apps.goods.models import SKU

# Create your views here.


class UserBrowseHistory(LoginRequiredMixin,View):
    """用户浏览记录"""

    def get(self,request):
        """获取用户浏览记录"""

        # 从数据库获取sku_id
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % request.user.id, 0, -1)

        # 根据sku_ids 列表，查询出商品sku信息
        skus = []
        for sku_id in sku_ids:
            try:
                sku = SKU.objects.get(pk=sku_id)
            except Exception as e:
                continue

            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price
            })
        # 返回响应
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'skus': skus
        })



    def post(self,request):
        """保存用户浏览记录"""

        # 接受参数
        data = json.loads(request.body)

        sku_id = data.get('sku_id')

        # 校验参数
        if not sku_id:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数缺失'})

        # 如果sku_id 是字符串，我们还要判断是否是纯数字
        if isinstance(sku_id,str) and not sku_id.isdigit():
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数错误'})
        try:
            # 数据处理
            # 获取history 缓存链接
            conn = get_redis_connection('history')

            # p1 = conn.pipeline()
            # lrem history_1 0 14  去重
            conn.lrem('history_%s' % request.user.id, 0, sku_id)

            # 写入历史记录
            # lpush history_1 14
            conn.lpush('history_%s' % request.user.id, sku_id)

            # 截取保留长度
            conn.ltrim('history_%s' % request.user.id, 0, 4)

            # p1.execute()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'redis存入失败'})

        # 构建响应
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class ChangePasswordView(View):
    """修改密码"""
    def put(self,request):

        # 获取参数
        data = json.loads(request.body)

        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')

        # 参数校验
        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 判断原密码是否正确
        if not request.user.check_password(old_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码不正确'})

        if not re.match(r'[0-9a-zA-Z]{8,20}', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码格式错误'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入的密码不一样'})

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()

        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改密码错误'})

        # 清理登录状态
        logout(request)

        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})
        response.delete_cookie('username')

        return response


class UpdateTitleAddressView(View):
    """修改地址标题"""

    def put(self,request, address_id):
        """修改地址标题逻辑"""

        # 获取参数
        data = json.loads(request.body)

        title = data.get('title')

        # 修改地址标题
        try:
            address = Address.objects.get(id=address_id)

            address.title = title
            address.save()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改地址失败'})

        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})



class DefaultAddressView(LoginRequiredMixin,View):
    """设置默认地址"""

    def put(self,request,address_id):
        """设置默认地址"""
        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address_id = address
            request.user.save()

        except Exception as e:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '设置默认地址失败'})

        return http.JsonResponse({'code': 0,
                             'errmsg': '设置默认地址成功'})



class UpdateAddressView(View):
    """修改和删除地址"""

    def put(self,request,address_id):
        """修改地址"""

        # 接受参数
        data = json.loads(request.body)

        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code': 0,
                             'errmsg': '更新地址成功',
                             'address': address_dict})


    def delete(self,request,address_id):
        """删除地址"""

        # 查询要删除的地址
        try:
            address = Address.objects.get(user=request.user,
                                             id=address_id)

            address.is_deleted = True
            address.save()

        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '删除地址失败'})
        return http.JsonResponse({'code': 0,
                             'errmsg': '删除地址成功'})


class AddressView(View):
    """用户收货地址"""

    def get(self,request):
        """提供地址管理界面"""

        # 获取所有地址
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)

        # 创建空列表
        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id ==address.id:
                # 查询集addresses 没有insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return http.JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'addresses': address_dict_list,
                             'default_address_id': default_id})



class CreateAddressView(View):
    """新增地址"""

    def post(self,request):
        """实现地址新增逻辑"""

        # 获取地址个数
        try:
            count = Address.objects.filter(user=request.user,is_deleted=False).count()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '获取地址数据出错'})

        # 判断地址个数
        if count >= 20:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '超过地址数量上限'})

        # 提取参数
        data = json.loads(request.body)

        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 校验参数
        if not all([receiver, province_id,city_id,district_id,place,mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '新增地址失败'})

        # 将新增地址响应给前端
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code': 0,
                             'errmsg': '新增地址成功',
                             'address':address_dict})


class VerifyEmailView(View):
    """验证邮箱"""

    def put(self,request):
        """实现邮箱验证逻辑"""
        # 接受参数
        token = request.GET.get('token')

        # 校验参数：判断 token 是否为空和过期，提取 user
        if not token:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '缺少token'})

        user = User.check_token(token)

        # 用户存在, 则修改email_active
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return http.JsonResponse({'code':400,
                                 'errmsg':'激活邮件失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailView(View):
    """添加邮箱"""
    def put(self,request):

        # 接收参数
        data = json.loads(request.body)

        email = data.get('email')

        # 校验邮箱
        if not email:
            return http.JsonResponse({'code': 400,
                                 'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '参数email有误'})

        # 添加email 的值
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': 0, 'errmsg': '添加邮箱失败'})

        # 通过封装的generate_token 加密token 生成verify_url
        verify_url = request.user.generate_token(email)

        # 生成发送邮箱验证任务,交由celery执行
        send_email_func.delay(email, verify_url)


        return http.JsonResponse({'code': 0,
                             'errmsg': '添加邮箱成功'})


class UserInfoView(LoginRequiredMixin, View):
    """用户中心页面访问"""

    # def get(self,request):
    #     """提供个人信息界面"""
    #
    #     # 判断用户是否登录
    #     if request.user.is_authenticated:
    #         data = {
    #             'username': request.user.username,
    #             'mobile': request.user.mobile
    #         }
    #         return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': data})
    #
    #     else:
    #         return http.JsonResponse({'code': 400, 'errmsg': '请先登录'})
# --------------------------------------------------------------------------------------

    # @method_decorator(my_decorator)
    # def get(self,request):
    #     """提供个人信息界面"""
    #     data = {
    #         'username': request.user.username,
    #         'mobile': request.user.mobile
    #     }
    #     return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': data})
# -----------------------------------------------------------------------------------------

    def get(self, request):
        """提供个人信息界面"""
        data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return http.JsonResponse({'code': 0, 'errmsg': 'ok','info_data': data})


class LogoutView(View):
    """退出登录"""

    def delete(self,request):
        """
        实现退出登录逻辑
        DELETE方式
        请求路径: /logout
        :param request:
        :return:
        """
        # 清理 session
        logout(request)

        # 创建response 对象
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 调用响应对象的delete_cookie 方法,清楚cookie
        response.delete_cookie('username')

        # 返回响应
        return response




class LoginView(View):
    """登录接口"""
    def post(self,request):
        """
        请求地址: /login/
        :param request:
        :return:
        """

        # 提取参数
        data_dict = json.loads(request.body)

        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')

        # 校验参数
        if not all([username,password]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': '用户名格式不对'})

        if not re.match(r'^[a-zA-Z0-9_]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码格式错误'})

        # 比对用户名和密码
        user = authenticate(request, username=username,password=password)

        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 状态保持
        login(request,user)

        # 判断是否记住用户
        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)  # 默认保持两周

        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24 * 14)

        # 返回响应
        return merge_cart_cookie_to_redis(request, user, response)


class RegisterView(View):
    """用户注册逻辑"""

    def post(self,request):
        """接收参数,保存到数据库"""

        # 接收参数
        data_dict = json.loads(request.body.decode())

        # 提取参数
        username = data_dict.get('username')
        password = data_dict.get('password')
        password2 = data_dict.get('password2')
        mobile = data_dict.get('mobile')
        sms_code = data_dict.get('sms_code')
        allow = data_dict.get('allow')


        # 校验参数
        if not all([username, password,password2,mobile,sms_code]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 3.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'username格式有误'})

        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'password格式有误'})

        # 5.password2 和 password
        if password != password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入不对'})
        # 6.mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'mobile格式有误'})
        # 7.allow检验
        if allow != True:
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'allow格式有误'})


        # sms_code 校验
        # 连接redis
        redis_conn = get_redis_connection('verify_code')

        # 取出redis 中的短信验证码
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 比较验证码
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '短信验证码错误'})
        # 创建用户保存到数据库
        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '创建用户失败'})

        # 状态保持
        login(request, user)

        response = http.JsonResponse({'code':0, 'errmsg': 'ok'})

        response.set_cookie('username',
                            user.username,
                            max_age=3600*24*14)

        # 返回响应
        return response



class MobileCountView(View):
    """手机号重复注册"""

    def get(self,request, mobile):
        """
        GET方式
        请求地址：/mobiles/(?P<mobile>1[3-9]\d{9})/count/
        :param request:
        :param mobile:
        :return:
        """

        # 校验参数
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式不对'})

        # 查询数据库中mobile的个数
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        # 返回结果
        return  http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})



class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self,request, username):
        """
        GET方式
        请求地址：/usernames/(?P<username>[a-zA-Z0-9_-]{5,20})/count/
        :param request:
        :return:
        """

        # 校验参数username
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     return http.JsonResponse({'code': 400, 'errmsg': 'username格式错误'})

        # 查询数据库中username的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        # 返回结果（json）   code  errmsg  count
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})


